/* eslint-disable */
/**
 * Created by GYL on 2018/8/24
 */
import React, { Component } from 'react';
import styles from '../EventPosting.less';
import { Divider, Collapse, Icon, Select, Input, notification, Form, Row, Col, TreeSelect, Tag, message, Spin ,Alert} from 'antd';
import Container from "../../../components/common/Container";
import PublicService from "../../../services/PublicService";
import config from '../../../config';
import Util from '../../../utils/Util';
import request from '../../../utils/request';
import MyTable from "../../../components/common/MyTable";
import MyModal from '../../../components/common/MyModal';
import JSGanttComponent from 'react-jsgantt';
import Alter_Edit_Wrap from './Alter_Edit_Wrap';
import Alter_Edit from './Alter_Edit';
import Alter_Edit_Small from './Alter_Edit_Small';
import moment from 'moment';
import Freeze_Appeal from './Freeze_Appeal';
const { Panel } = Collapse;
const { Option } = Select;
const { TextArea } = Input;
const FormItem = Form.Item;
const { SHOW_CHILD } = TreeSelect;
const text = `
  A dog is a type of domesticated animal.
  Known for its loyalty and faithfulness,
  it can be found as a welcome guest in many households across the world.
`;
var indexNum = 1
const IconFont = Icon.createFromIconfontCN({
  scriptUrl: '//at.alicdn.com/t/font_1315525_mwxuxnny2l.js',
});
class Alter_GtteWrap extends Component {




  constructor(props) {
    super(props);

    const vAdditionalHeaders = {
      pzState: { title: '配置状态' },
      planStartTime: { title: '计划开始时间', width: 200 },
      planEndTime: { title: '计划结束时间' },
      workTime: { title: '工期' },
      proposeTask: { title: '前置任务' },
      number: { title: '序号' }
    };

    this.state = {
      EditDataSmall: {},
      MyModal1VisibleSmall: false,
      MyModal1Visible: false,
      title: '项目xx编辑',
      addWrap: false,
      Alter_Edit_Wrap: false,
      data: [],
      editWrap: false,
      EditArr: [],
      EditData: {},
      count: 0,
      Edit_Appeal: false,
      spinning: false
    }






    this.editorOptions = {
      vCaptionType: 'Complete',  // Set to Show Caption : None,Caption,Resource,Duration,Complete,控制右边图形结尾显示
      vQuarterColWidth: 36,
      vDateTaskDisplayFormat: ' yyyy-mm-dd', // Shown in tool tip box
      vDayMajorDateDisplayFormat: ' yyyy-mm-dd', // Set format to display dates in the "Major" header of the "Day" view
      vWeekMinorDateDisplayFormat: 'dd 日', // Set format to display dates in the "Minor" header of the "Week" view
      vLang: 0,
      vUseSingleCell: 0,
      vShowRes: 0,
      vShowCost: 0,
      vShowComp: 0,
      vShowDur: 0,
      vShowStartDate: 0,
      vShowEndDate: 0,
      vShowPlanStartDate: 0,
      vShowPlanEndDate: 0,
      vShowTaskInfoEndDate: 0,
      vShowTaskInfoLink: parseInt(this.vShowTaskInfoLink, 10), // Show link in tool tip (0/1)
      // Show/Hide the date for the last day of the week in header for daily view (1/0)
      // vTaskInfo: 0,
      vAdditionalHeaders: vAdditionalHeaders,//左边表格头部
      vEvents: {
        taskname: this.onEvent.bind(this, this.state.data),//点击触发
        res: 0,
        dur: 0,
        comp: 0,
        start: 0,
        end: 0,
        planstart: 0,
        planend: 0,
        cost: 0
      },
      vEventsChange: {
        taskname: this.editValue.bind(this, this.state.data),//编辑触发
        res: this.editValue.bind(this, this.state.data),
        dur: this.editValue.bind(this, this.state.data),
        comp: this.editValue.bind(this, this.state.data),
        start: this.editValue.bind(this, this.state.data),
        end: this.editValue.bind(this, this.state.data),
        planstart: this.editValue.bind(this, this.state.data),
        planend: this.editValue.bind(this, this.state.data),
        cost: this.editValue.bind(this, this.state.data)
      },
      vResources: [
        { id: 0, name: 'Anybody' },
        { id: 1, name: 'Mario' },
        { id: 2, name: 'Henrique' },
        { id: 3, name: 'Pedro' }
      ],
      // vEventClickRow: console.log,
      vTooltipDelay: 1,
      vDebug: false,
      vEditable: false,//是否可以编辑
      vUseSort: 'true',
      vFormatArr: ['Day', 'Week', 'Month'],//切换控制日期选择,日,周,月
    };
  }

  componentDidMount() {
    // console.log(this.props)
    this.getGanttDataThree()
  }

  //获取甘特图数据
  getGanttDataThree = () => {
    this.setState({
      spinning: true
    })
    let params = {
      changeId: this.props.changeId,
      projectId: this.props.id
    }
    request({
      url: '/pm-web/projectmanage/progress/getGanttDataThree',
      method: 'POST',
      data: params
    }).then(data => {
      if (data.rc === 0) {
        this.setState({
          data: data.ret.ganttList,
          count: data.ret.count,
          spinning: false
        })
      }
    })
  }

  editValue(list, task, event, cell, column) {
    // tslint:disable-next-line:triple-equals
    const found = list.find(item => item.pID == task.getOriginalID());
    if (!found) {
      return;
    } else {
      found[column] = event ? event.target.value : '';
    }
    // console.log(found);
  }

  change() {
    // console.log('change:', this.editor);
    // console.log('change2:', this.editorTwo);
  }

  setLanguage(lang) {
    this.editorOptions.vLang = lang;
    this.editor.setOptions(this.editorOptions);
  }

  customLanguage() {
    // this.editorOptions.languages = {
    //   'pt-BR': {
    //     'auto': 'Automático testing'
    //   },
    //   'en': {
    //     'auto': 'Auto testing'
    //   }
    // };
    this.editor.setOptions(this.editorOptions);
  }

  changeObject() {
    this.state.data.randomNumber = Math.random() * 100;
  }

  changeData() {
    this.state.data = Object.assign({}, this.state.data,
      { randomNumber: Math.random() * 100 });
  }



  // 取消保存
  ModalCancel = (type) => {
    let t = this;
    t.setState({
      [type]: false,
      modalBtnLoading: false
    })
  };






  //保存按钮事件
  onModalSave = (v) => {
    // console.log(v, 44)
    let params = {
      eventId: this.state.eventId,
      milepost: v.milepost,
      userIds: v.safetyInformationList,
      changeId: this.props.changeId,
      projectId: this.props.id
    }
    request({
      url: '/pm-web/projectmanage/eventinfo/updateEventInfoTwo',
      method: 'POST',
      data: params
    }).then(data => {
      if (data.rc === 0) {
        message.success("修改成功")
        this.getGanttDataThree()
      } else {
        message.warning("修改失败")
      }


    })


  }


  selectedChange(fun, nextParams, paramName, index, value) {
    // console.log(fun, nextParams, paramName, index, value)


    let t = this;
    let params = {};
    params[paramName] = value;
    if (paramName) {
      t.setState({ params }, () => {
      });
    }
    if (typeof fun === "function") {
      fun(value);
      if (nextParams)
        t.props.form.setFieldsValue({
          [nextParams]: ''
        })
    }
  }

  onEdit = () => {
    this.setState({
      Alter_Edit_Wrap: true
    })
  }

  onEvent = (list, task, event, cell, column) => {
    // console.log(list, task.getLink(), event, cell, column)
    // task.getOriginalID()  获取点击项目的id
    // console.log(task.getGroup(),  task.getParent(), task.getOriginalID(),task.getParItem().getOriginalID(),task)

    if (task.getParent() == 0) {
      return
    }

    if (Number(task.getParItem().getOriginalID() < 5)) {
      //大事件
      request({
        url: '/pm-web/projectmanage/eventinfo/findOneEventInfo',
        method: 'POST',
        data: { eventId: task.getOriginalID(), changeId: this.props.changeId, projectId: this.props.id }
      }).then(data => {
        // console.log(data)
        if (data.rc === 0) {
          this.setState({
            EditData: data.ret,
            MyModal1Visible: true,
            eventId: task.getOriginalID()
          })


        }
      })
    } else {
      //小事件
      request({
        url: '/pm-web/projectmanage/subeventsInfo/findOneSubeventsInfo',
        method: 'POST',
        data: { subeventsId: task.getOriginalID(), changeId: this.props.changeId, projectId: this.props.id }
      }).then(data => {
        // console.log(data)
        if (data.rc === 0) {
          this.setState({
            EditDataSmall: data.ret,
            MyModal1VisibleSmall: true,
            subeventsId: task.getOriginalID(),
            eventId: task.getOriginalID()
          })


        }
      })
    }




  }
  //子事件保存
  onModalSaveSmall = (v) => {
    // console.log(v, 44)
    let params = {
      confirmUserId: v.confirmUserId,
      planEndTime: moment(v.planEndTime).format("YYYY-MM-DD"),
      planStartTime: moment(v.planStartTime).format("YYYY-MM-DD"),
      subeventsId: this.state.subeventsId,
      subeventsWeight: v.subeventsWeight,
      workTime: v.workTime,
      auditCcUsers: v.auditCcUsers,
      auditUsers: v.auditUsers,
      changeId: this.props.changeId,
      projectId: this.props.id,
      oaUserArr: v.oaUserArr,
      userIds: v.safetyInformationUser,
      milepost: v.milepost
    }
    request({
      url: '/pm-web/projectmanage/subeventsInfo/updateEventInfoThree',
      method: 'POST',
      data: params
    }).then(data => {
      if (data.rc === 0) {
        message.success("修改成功")
        this.getGanttDataThree()
      } else {
        message.warning("修改失败")
      }

      this.setState({
        MyModal1VisibleSmall: false
      })


    })

  }

  fanhui = () => {
    this.props.fanhui()
  }

  fanhui2 = () => {
    this.setState({
      Alter_Edit_Wrap: false
    })
    //刷新甘特图
    this.getGanttDataThree()
  }

  //onBack 审批提交返回
  onBackAppeal = () => {
    this.setState({
      Edit_Appeal: false,

    })

  }


  onWbs = () => {

  }


  //确认解冻
  onSave = () => {

    this.setState({
      spinning:true
    })
  
    request({
      url: '/pm-web/projectmanage/progress/submitChangeApprovalOne',
      method: 'POST',
      data: { projectId: this.props.id, changeId: this.props.changeId }
    }).then(data => {

      if (data.rc === 0) {
        this.setState({
          Edit_Appeal: true
        })

      } else {
        message.warning(`${data.err}`)
      }
      this.setState({
        spinning:false
      })
    })
  }

  onBackAll = () => {
    this.props.onBackAll()
  }

  render() {
    let t = this
    let width = document.body.clientWidth;
    const height = document.body.clientHeight;
    let containerHeight = '76vh';
    let tableHeight = 310;
    if (width > 1367) {
      tableHeight = 380;
      containerHeight = '83vh';
    }

    const openNotification = () => {
      notification.open({
        message: 'WBS分解提示',
        description:
          '已通知审算部人员进行WBS分解.',
        onClick: () => {
          // console.log('Notification Clicked!');
        },
      });
    };


    return (
      <div>
        {
          this.state.Alter_Edit_Wrap ? <Alter_Edit_Wrap changeId={this.props.changeId} id={this.props.id} fanhui2={this.fanhui2} /> : this.state.Edit_Appeal ? <Freeze_Appeal changeId={this.props.changeId} id={this.props.id} onBackAppeal={this.onBackAppeal} onBackAll={this.onBackAll} /> : <div className={styles.warpBox}>

            {/* <div className={styles.Top_Box} style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 0, border: '2px solid #fff', borderRadius: '6px 6px 0px 0px', height: 20, alignItems: 'center' }}>

            </div> */}
            {
              this.props.frozenReasons?<Alert message={` 冻结理由 : ${this.props.frozenReasons}`} type="warning" banner closable/>:''
            }
            
            <Spin tip="Loading..." spinning={this.state.spinning}>
              
              <div className={styles.Top_Box} style={{ backgroundColor: '#fff', height: 40, alignItems: 'center', paddingLeft: 15 ,display:'flex'}}>

                <span style={{ padding: 3, marginLeft: 15, cursor: 'pointer', color: '#3996FF', display: 'contents' }} onClick={this.onEdit}>
                  <IconFont type="icon-bianji" />  编辑</span>
                <Divider type="vertical" />

                <span style={{ fontSize: 14, cursor: 'pointer', width: 20, height: 20, color: '#F58989', display: 'contents' }} onClick={this.onSave}>
                  <IconFont type="icon-shenpi" />  确认解冻</span>
                <Divider type="vertical" />

                <span >未完成配置数量 : ( {this.state.count} )</span>
              </div>

              <div style={{ backgroundColor: '#f6f6f18a', overflow: 'auto', height: '80vh' }} className={styles.gantt}>
                {/* 大事件编辑页面 */}
                {
                  this.state.MyModal1Visible && <Alter_Edit
                    ModalCancel={this.ModalCancel.bind(this, 'MyModal1Visible')}
                    EditData={this.state.EditData}
                    onModalSave={this.onModalSave}
                    onCancel={this.ModalCancel.bind(this, 'MyModal1Visible')}
                    visible={this.state.MyModal1Visible}
                  />
                }
                {/* 小事件编辑页面 */}
                {
                  this.state.MyModal1VisibleSmall && <Alter_Edit_Small
                    onCancel={this.ModalCancel.bind(this, 'MyModal1VisibleSmall')}
                    EditData={this.state.EditDataSmall}
                    onModalSave={this.onModalSaveSmall}
                    visible={this.state.MyModal1VisibleSmall}
                  />
                }
                <div style={{ flex: 1, overflow: 'auto' }}>
                  <JSGanttComponent data={this.state.data} options={this.editorOptions} />
                </div>
              </div>
            </Spin>
          </div>
        }

      </div>
    );


  }

}
export default Alter_GtteWrap;

